<template>
  <div style="margin: 20px;">
    <el-row>
      <el-col  :span="2">
        <el-input  placeholder="请输入订单编号"  v-model="SelectCommodityForm.commodityId"  style="width: 150px; margin-right: 10px;"  @change="selsectcommodityId" />
      </el-col>
      <el-col :push="2" :span="2">
        <el-input  placeholder="请输入收货地址"  v-model="SelectCommodityForm.addressInfo"  style="width: 150px; margin-right: 10px;"  @change="selsectaddressInfo" />
      </el-col>

      <el-col :push="4" :span="2">
        <el-input  placeholder="请输入名字"  v-model="SelectCommodityForm.receiverName"  style="width: 150px; margin-right: 10px;"  @change="selsectreceiverName" />
      </el-col>
      <el-col :push="6" :span="2">
        <el-input  placeholder="请输人收货人电话"  v-model="SelectCommodityForm.receiverPhone"  style="width: 150px; margin-right: 10px;"  @change="selsecreceiverPhone" />
      </el-col>

      <el-col :push="8" :span="2">
  <el-select v-model="SelectCommodityForm.paymentStatus" placeholder="请选择支付状态"  style="width: 150px" @change="selsectpaymentStatus">
    <el-option
      v-for="item in cities"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    /></el-select>
      </el-col>

      <el-col :push="10" :span="2">
  <el-select v-model="SelectCommodityForm.shippingStatus" placeholder="请选择发货状态"  style="width: 150px" @change="selsectpaymentStatus">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    /></el-select>
      </el-col>
    </el-row>



    <el-row style="margin-top: 10px;">
      <el-col :push="22" :span="2">
        <el-dropdown trigger="click">
          <span class="el-dropdown-link" >
            待处理业务
            <el-icon class="el-icon--right"><caret-bottom /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item class="clearfix" @click="ccc" type="warning">
                待退款
                <el-badge class="mark" :value="RefundCommodityTotal" />
              </el-dropdown-item>
              <el-dropdown-item class="clearfix"   @click="PendingShipment" >
                待发货
                <el-badge class="mark" :value="PendingShipmentCommodityTotal"/>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
    </el-row>

    <div v-for="(order, index) in orderData" :key="index" style="margin-top: 20px;">
      <el-descriptions :title="`订单 ${index + 1} 信息`" :column="2" border>
        <el-descriptions-item label="订单编号">{{ order.commodityId }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDate(order.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ order.receiverName }} ({{ order.receiverPhone }})</el-descriptions-item>
        <el-descriptions-item label="地址">{{ order.addressInfo }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">{{ paymentStatusText(order.paymentStatus) }}</el-descriptions-item>
        <el-descriptions-item label="发货状态">{{ shippingStatusText(order.shippingStatus) }}</el-descriptions-item>
        <el-descriptions-item label="退款状态" v-if="order.refund!=0">{{ refundText(order.refund) }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="order.commodityDetails || []" style="width: 100%; margin-top: 20px;" stripe>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="单价" width="180">
          <template #default="scope">￥{{ scope.row.price }}</template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="180"></el-table-column>
        <el-table-column label="总价" width="180">
          <template #default="scope">￥{{ scope.row.totalPrice }}</template>
        </el-table-column>
        <el-table-column prop="notes" label="备注"></el-table-column>
      </el-table>

      <div class="order-total" style="text-align: right; margin-top: 20px;">
        <el-row>
            <el-col :span="4">
              <span >订单总金额：￥{{ order.total }}</span>
            </el-col>

            <el-col :push="14" :span="4">
              <span>折扣后价格：￥{{ order.discountedPrices }}</span>
            </el-col>
          </el-row>
        <!-- <el-button type="primary" v-if="order.shippingStatus === 0 && order.paymentStatus==1" @click="placeOrder()" style="margin-left: 20px;">发货</el-button> -->
      </div>
      <hr />
    </div>

    <el-dialog v-model="isShow3" title="退款订单处理" width="500">
      <span>
        <p>退款订单处理</p>
        <p>当前有：{{ RefundCommodityTotal }}条待处理退款订单</p>
        <p>是否前往处理退款订单？</p>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShow3 = false">取消</el-button>
          <el-button @click="handle">确认前往</el-button>
        </div>
      </template>
    </el-dialog>

    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="SelectCommodityForm.pageNum"
        v-model:page-size="SelectCommodityForm.pageSize"
        :page-sizes="[1, 4, 6, 8]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'OrderDetail',
  data() {
    return {
      orderData: [], // 初始化为空数组
      SelectCommodityForm: {
        pageNum: 1,
        pageSize: 10,
        commodityId: null,
        addressInfo: null,
        receiverName: null,
        receiverPhone: null,
        paymentStatus: null,
        shippingStatus: null,
        createdAt: null,
      },
      total: 0,
      RefundCommodityList: [],
      RefundCommodityTotal: 0,
      SelectRefundCommodityForm: {
        pageNum: 1,
        pageSize: 10,
        commodityId: null,
        addressInfo: null,
        receiverName: null,
        receiverPhone: null,
        paymentStatus: null,
        shippingStatus: null,
        createdAt: null,
      },
      SelectPendingShipmentCommodityManagerForm:{
        pageNum: 1,
        pageSize: 10,
        commodityId: null,
        addressInfo: null,
        receiverName: null,
        receiverPhone: null,
        paymentStatus: null,
        shippingStatus: null,
        createdAt: null,
      },
      PendingShipmentCommodity:[],
      PendingShipmentCommodityTotal:0,
      isShow3: false,
      intervalId: null, // 用于存储定时器ID
      cities: [
        { label: '未支付', value: '0' },
        { label: '已支付', value: '1' },
        { label: '全部', value: null },
      ],
      options:[
        { label: '全部', value: null },
        { label: '未发货', value: '0' },
        { label: '已发货', value: '1' },
        { label: '已签收', value: '2' },
        { label: '退货中', value: '3' },
        { label: '已退货', value: '4' },
      ]
    };
  },
  methods: {
    selsectpaymentStatus(){
      console.log(this.SelectCommodityForm.paymentStatus);
      this.selsectcommodity();

    },
    selsecreceiverPhone(){
      if (this.SelectCommodityForm.receiverPhone == null) {
        alert("请输入收货人电话");
        return;
      }
      this.selsectcommodity();
    },
    selsectreceiverName(){
      if (this.SelectCommodityForm.receiverName == null) {
        alert("请输入收货人名字");
        return;
      }
      this.selsectcommodity();
    },

    selsectaddressInfo(){
      if (this.SelectCommodityForm.addressInfo == null) {
        alert("请输入订单地址");
        return;
      }
      this.selsectcommodity();

    },
    PendingShipment(){
      this.$router.push("/managerpendingshipment");
    },
    getPendingShipmentCommodity() {
      this.$http.post("/order/commodity/selsectpendingshipmentcommoditymanager",this.SelectPendingShipmentCommodityManagerForm)
        .then(resp => {
          this.PendingShipmentCommodity = resp.data.data.list;
          
          this.PendingShipmentCommodityTotal = resp.data.data.total;
          if (this.PendingShipmentCommodityTotal == 0) {
            this.$message.error("没有待发货订单");
          }
        }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
   
    ccc() {
      this.$router.push("/managerrefundcommodity");
    },
    selsectcommodityId() {
      if (this.SelectCommodityForm.commodityId == null) {
        alert("请输入订单编号");
        return;
      }
      this.selsectcommodity();
    },
    handle() {
      this.$router.push("/managerrefundcommodity");
    },
    selsectRefundCommodity() {
      this.$http.post('/order/commodity/selsectrefundcommoditymanager', this.SelectRefundCommodityForm)
        .then(resp => {
          this.RefundCommodityList = resp.data.data.list;
          this.RefundCommodityTotal = resp.data.data.total;
          if (this.RefundCommodityTotal > 0) {
            this.isShow3 = true;
          }
          if (this.RefundCommodityTotal == 0) {
            this.$message.error('没有退款订单');
          }
        }).catch(error => {
          console.error("获取失败:", error);
          this.$message.error("获取失败，请稍后再试。");
        });
    },
    handleSizeChange(val) {
      this.SelectCommodityForm.pageSize = val;
      this.selsectcommodity();
    },
    handleCurrentChange(val) {
      this.SelectCommodityForm.pageNum = val;
      this.selsectcommodity();
    },
    selsectcommodity() {
      this.$http.post('/order/commodity/selsectcommoditymanager', this.SelectCommodityForm)
        .then(resp => {
          this.orderData = resp.data.data.list;
          this.orderData.sort((a, b) => {
                return (b.paymentStatus - a.paymentStatus); // 1 - 0 = 1，保持 1 在前
            });
          this.total = resp.data.data.total;
        }).catch(error => {
                  this.$message.error('请求失败，请重试。');
                  console.error(error);
              })
    },
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    refundText(status){
    const statusMap = {
      0: '未申请退款',
      1: '待处理',
      2: '已同意',
      3: '已拒绝',
    };
    return statusMap[status] || '未知状态';
  },
    paymentStatusText(status) {
      return status === 1 ? '已支付' : '未支付';
    },
    shippingStatusText(status) {
      const statusMap = ['未发货', '已发货', '已签收', '退货中', '已退货'];
      return statusMap[status] || '未知状态';
    },
    startPolling() {
      this.intervalId = setInterval(() => {
        this.selsectcommodity(); // 定期获取订单数据
        this.selsectRefundCommodity();
        this.getPendingShipmentCommodity();
      }, 60000); // 每5秒轮询
    },
    stopPolling() {
      clearInterval(this.intervalId); // 清理定时器
    }
  },
  mounted() {
    this.selsectcommodity();
    this.selsectRefundCommodity();
    this.getPendingShipmentCommodity();
 
    this.startPolling(); // 开始轮询
  },
  beforeUnmount() {
    this.stopPolling(); // 组件卸载前清理定时器
  }
};
</script>

<style scoped>
/* 样式可以根据需要调整 */

.el-dropdown-link {
  color: #5DE2E7; /* 改变为你想要的颜色 */
}
</style>